import { app, ipcMain, globalShortcut, BrowserWindow } from "electron";
import * as remote from "@electron/remote/main";

import { windows, closeWindowById } from "./jc-electron-tools/windows";
import { newWinMain } from "./apps/Desktop";
import { newWinUser } from "./apps/User";
import { newWinAdmin } from "./apps/Admin";
import { fileAssociationsOpen } from "./associations/file";
import { User } from "./database/user";
import { windowManagerIPC } from './ipc'
import { logger } from "./settings";
import { HTTPRequesrsIPC } from "./ipc/http";
import { stateManagerIpc } from "./ipc";
import { auth } from '@/store';
import { ipcStateSynchronization } from "@/event";
import { UserLoginEvent } from "@/enums";

async function bootstrap() {
  // 此方法的返回值指示应用程序的此实例是否成功获得锁。如果它未能获得锁，您可以假设应用程序的另一个实例已经带着锁运行并立即退出。
  const gotTheLock = app.requestSingleInstanceLock(windows);
  if (!gotTheLock) {
    app.quit();
  } else {

    app.on("will-finish-launching", () => {
      app.on("open-file", (event, path: string) => {
        event.preventDefault();
        path && fileAssociationsOpen(path);
      });
    });

    // 当执行第二个实例并调用app.requestSingleInstanceLock()时，将在应用程序的主实例内部发出此事件。
    app.on(
      "second-instance",
      (event, argv, workingDirectory, additionalData) => {
        if (process.platform !== "darwin") {
          const path = argv[argv.length - 1]; // 最后一个参数是文件绝对路径
          path && fileAssociationsOpen(path);
        }
      }
    );

    let userWindowId = "";

    // 当electron初始化时完成。可用作检查app.isReady()并在应用程序尚未就绪时订阅就绪事件的便捷替代方法。
    await app.whenReady().then(async () => {
        remote.initialize();
        userWindowId = newWinUser()
        newWinAdmin();
      });
      stateManagerIpc();  // 状态同步器通讯
      windowManagerIPC(); // 窗口管理器通讯
      HTTPRequesrsIPC();



      // 登陆成功
      ipcStateSynchronization(UserLoginEvent,(data:{token:string})=>{
        const token = data.token;
        logger.debug(`响应发布的状态同步事件，token =`,token);
        closeWindowById(userWindowId); // 关掉用户窗口
        newWinMain();                  // 打开桌面窗口（主窗口）
      })

  }
}

(async ()=>{
  // TODO: 可以屏蔽安全警告，但是最好放在配置文件中，区别是开发还是生产环境
  process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = "true";
  await bootstrap()
})();